import { wss } from '../ws.js'
import { nanoid } from 'nanoid'
import { movePoint } from '../utils/tools.js'
import fs from 'fs'
import path from 'path'

/**
 * critRate 暴击几率
 * critDmg 暴击伤害
 */
const data = {
  '000': [
    {
      count: 3,
      data: {
        type: 'm1',
        name: '野猫',
        level: 4,
        hp: 100,
        rHp: 100,
        maxAtk: 5,
        minAtk: 20,
        critRate: 0.15,
        critDmg: 1.5,
      },
    },
  ],
}
const coordinates = []
const curMap = '000'
const currentDir = process.cwd()
const filePath = path.join(currentDir, `./game/${curMap}.json`)
const rawData = fs.readFileSync(filePath, 'utf8')
const mapInfo = JSON.parse(rawData)
data[curMap].forEach((item) => {
  for (let i = 0; i < item.count; i++) {
    const x = Math.floor(Math.random() * mapInfo.width)
    const y = Math.floor(Math.random() * mapInfo.height)
    coordinates.push({ id: nanoid(), x, y, ...item.data })
  }
})

wss.on('connection', (ws) => {
  ws.on('error', console.error)

  // ws.send(
  //   JSON.stringify({
  //     type: 'monster',
  //     data: coordinates,
  //   })
  // )
  init(ws)
})

let timer = null

function init(ws) {
  for (let i = 0; i < coordinates.length; i++) {
    const item = coordinates[i]
    movePoint(item)
  }

  const result = {
    type: 'monster',
    data: coordinates,
  }
  ws.send(JSON.stringify(result))

  clearTimeout(timer)
  timer = setTimeout(() => init(ws), 3000)
}

export function getMonster() {
  return coordinates
}
